<template>
  <div v-show="relateName" class="mb-4 flex flex-row items-center">
    <span class="mr-2">关联{{ relateName }}</span>
    <a-input
      v-model:value="selText"
      class="!w-56 cursor-pointer"
      readonly
      :placeholder="'请点击选择' + relateName"
      :disabled="!!options.curReceipt"
      @click="showSelectModal"
    />
    <a v-if="selText && !options.curReceipt" class="text-color-danger ml-2" @click="cancel">取消关联</a>
    <a-modal
      v-model:visible="visible"
      :title="'选择' + relateName"
      :width="800"
      :body-style="{ padding: 0 }"
      @ok="handleSel"
    >
      <TableSelect
        ref="selectIns"
        v-model:value="selIds"
        :search-placeholder="searchTip"
        :extra-params="extraParams"
        search-key="keywords"
        :columns="columns"
        :get-page-url="pageApi"
        :field-names="{ value: 'id', label: noKey }"
        selected-width-cls="w-72"
        single-select
      >
        <template #bodyCell="{ column, record }: BodyCellOptions<Partial<ReceiptItem>>">
          <StatusCell v-if="column.dataIndex === 'status'" :status="record.status" />
          <FitTitleCell v-else :column="column" :record="record" />
        </template>
      </TableSelect>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { filterColumns, getLabelByValueFromEnum } from "/@/utils/common";
import { PurchaseOrderType, ReceiptItem, ReceiptType } from "/@/api/main/pis/models";
import { Api } from "/@/api/main/pis";
import { Api as financialApi } from "/@/api/main/financial";
import dayjs from "dayjs";
import { SelectExpose } from "/@/types/components";
import { TableColumnProps, message } from "ant-design-vue";
import { BodyCellOptions } from "/@/types/antd";
import StatusCell from "./StatusCell.vue";
import { RelateOrderExpose, RelateOrderOptions, useReceiptManage } from "./useReceiptManage";
import { FinancialItem, FinancialType, PayOpType } from "/@/api/main/financial/models";
import { usePayment } from "/@/views/main/financial/usePayment";

const props = defineProps<{
  options: RelateOrderOptions;
  receiptType: ReceiptType;
}>();
const emits = defineEmits(["select", "init", "relate"]);

let relateName = "",
  searchTip = "",
  pageApi = "",
  noKey = "",
  noKeyInCurReceipt = "",
  idKeyInCurReceipt = "",
  requiredRelate = false,
  relateReceiptType: ReceiptType | null = ReceiptType.purchase,
  extraParams: any = undefined,
  relateFinancialType: FinancialType | null = null,
  disableFormKeys: string[] = [],
  disableAddGood = false;
switch (props.receiptType) {
  case ReceiptType.warehousing:
    //入库单关联采购订单
    relateName = "采购订单";
    searchTip = "搜索采购订单号/供应商/采购员";
    pageApi = Api.purchaseReceiptPage;
    noKey = "orderNo";
    noKeyInCurReceipt = "purchaseOrderNo";
    idKeyInCurReceipt = "purchaseOrderId";
    disableFormKeys = ["supplierId", "warehouseId"];
    disableAddGood = true;
    break;
  case ReceiptType.return:
    //客户退货单关联销售单
    relateName = "销售单";
    searchTip = "搜索销售单单号/供应商/仓库";
    pageApi = Api.sellReceiptPage;
    noKey = "goodsSaleNo";
    noKeyInCurReceipt = "saleOrderNo";
    idKeyInCurReceipt = "saleOrderId";
    relateReceiptType = ReceiptType.sell;
    disableAddGood = true;
    break;
  case ReceiptType.purchase:
    //采购订单关联付款单
    relateName = "付款单";
    searchTip = "搜索付款单号";
    pageApi = financialApi.paymentPage;
    noKey = "orderNo";
    noKeyInCurReceipt = "paymentReceiptNo";
    idKeyInCurReceipt = "paymentReceiptId";
    relateReceiptType = null;
    relateFinancialType = FinancialType.payment;
    extraParams = { opType: PayOpType.pay };
    disableAddGood = false;
    break;
}

onMounted(() => {
  emits("init", {
    requiredRelate,
    relateReceiptType,
    relateName,
    relateFinancialType,
    disableFormKeys,
    disableAddGood,
  });
});

let innerColumns: TableColumnProps<any>[] = [];
if (relateReceiptType) {
  const re = useReceiptManage(relateReceiptType);
  innerColumns = re.innerColumns;
  filterColumns(innerColumns, ["oper"]);
} else if (relateFinancialType) {
  if (relateFinancialType === FinancialType.payment) {
    const e = usePayment(["oper"]);
    innerColumns = e.columns;
  }
}
const columns = ref<TableColumnProps<any>[]>(innerColumns);

const visible = ref(false);
function showSelectModal() {
  if (props.options.curReceipt) return;
  visible.value = true;
}

const selIds = ref<number[]>([]);
const selText = ref("");
const selectIns = ref<SelectExpose>();
function handleSel() {
  if (selIds.value.length === 0) return message.info("请选择" + relateName);
  if (selectIns.value) {
    const items = selectIns.value.getSelecedItems() as any;
    selText.value = items[0][noKey];
    visible.value = false;
    emits("select", items[0]);
  }
}

watch(
  () => props.options,
  (options) => {
    if (options.reset) {
      selText.value = "";
      selIds.value = [];
    } else if (options.curReceipt) {
      //获取所关联的单的单号
      if (noKeyInCurReceipt) {
        selText.value = options.curReceipt[noKeyInCurReceipt] as string;
        selIds.value = [];
        if (selText.value) {
          emits("relate");
        }
      }
    }
  }
);

function cancel() {
  selText.value = "";
  emits("select", null);
}

defineExpose<RelateOrderExpose>({
  relateCurReceipt(curReceipt, relateReceipt) {
    curReceipt[noKeyInCurReceipt] = relateReceipt[noKey];
    curReceipt[idKeyInCurReceipt] = relateReceipt.id;
  },
});
</script>
